document.addEventListener('DOMContentLoaded', (event) => {
    document.getElementById('userInput').addEventListener('keydown', function(event) {
        if (event.key === 'Enter') {
            sendMessage();
        }
    });
});
async function sendMessage() {
    const apiEndpoint = document.getElementById('apiEndpoint').value || "http://localhost:11434/api/chat";
    const modelName = document.getElementById('modelName').value || "deepseek-r1:1.5b";
    const role = "user";
    const userInput = document.getElementById('userInput').value;

    if (!userInput) {
        alert('Please enter your message.');
        return;
    }

    const chatBox = document.getElementById('chatBox');
    const userMessageDiv = document.createElement('div');
    userMessageDiv.className = 'message user';
    userMessageDiv.textContent = '我: ' + userInput;
    chatBox.appendChild(userMessageDiv);

    const requestBody = {
        model: modelName,
        messages: [{ role: role, content: userInput }],
        stream: false
    };

    try {
        const response = await fetch(apiEndpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestBody),
        });

        const responseText = await response.text();
        const data = JSON.parse(responseText);
        // console.log('Parsed Response:', data); // Log the parsed response for debugging
        botMessageContent = data.message.content.replace(/<\/?think>/g, '');
        // Extract and format the think content as a comment
        const thinkContent = data.message.content.match(/<think>(.*?)<\/think>/g);
        let thinkComment = '';
        if (thinkContent) {
            thinkComment = thinkContent.map(content => content.replace(/<\/?think>/g, '')).join('\n');
            thinkComment = `/* ${thinkComment} */\n`;
        }

        const botMessageDiv = document.createElement('div');
        botMessageDiv.className = 'message bot';
        botMessageDiv.textContent = '机器人: ' + thinkComment + botMessageContent;
        chatBox.appendChild(botMessageDiv);

        chatBox.scrollTop = chatBox.scrollHeight;
    } catch (error) {
        alert('Error: ' + error.message);
    }

    document.getElementById('userInput').value = '';
}
